/*
Copyright (C) Ariff Ehsan, Abdul Hadi Fikri

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

/*  Author : Ariff Ehsan
 *  Date   : June 29, 2009
 */


#include <system.h>

uint8_t app_count;
BOOL app_motor_state = FALSE;

timer_t app_timer;
button_t app_button;

void APP_TIMER_run(void);
void APP_BUTTON_event(uint8_t);

void APP_booted(){
	
	/* initialize */
	LEDS8_init();
	MOTOR_init();
	BUTTON_init();
	
	/* set button pin as input pin */
	CLR_BIT(DDRB, PB0);
	
	/* wire button */
	BUTTON_reg(&app_button, (uint8_t*)&PINB, PB0, APP_BUTTON_event);
	BUTTON_start(&app_button);
	
	/* wire timer */
	TIMER_reg(&app_timer, APP_TIMER_run);
	
	/* start periodic timer */
	TIMER_startPeriodic(&app_timer, 1000);
	
	MOTOR_setSpeed(MOTOR_RIGHT, 200);
	MOTOR_setSpeed(MOTOR_LEFT, 200);
	
}

void APP_TIMER_run(void) {
	
	app_count++;
	//LEDS8_set(app_count);
	
}

void APP_BUTTON_event(uint8_t state) {
	
	if (state == BUTTON_PUSHED) {
		if (app_motor_state) {
			app_motor_state = FALSE;
			
			MOTOR_setDir(MOTOR_RIGHT, MOTOR_STOP);
			MOTOR_setDir(MOTOR_LEFT, MOTOR_STOP);
			
			LEDS8_off(0);
		}
		else {
			app_motor_state = TRUE;
			
			MOTOR_setDir(MOTOR_RIGHT, MOTOR_BACKWARD);
			MOTOR_setDir(MOTOR_LEFT, MOTOR_BACKWARD);
			
			LEDS8_on(0);
		}
	}
	
}
